/* eslint-disable @typescript-eslint/no-explicit-any */
import { Monaco } from "@monaco-editor/react";
// import { JsxEmit } from "typescript";
import {
  getWorker,
  MonacoJsxSyntaxHighlight,
} from "monaco-jsx-syntax-highlight";
import { createATA } from "../../utils/ata";

export const typeHelper = createATA();

function useEditor() {
  // 点击变量跳转
  const doOpenEditor = (editor: any, input: any) => {
    const selection = input.options ? input.options.selection : null;
    if (selection) {
      if (
        typeof selection.endLineNumber === "number" &&
        typeof selection.endColumn === "number"
      ) {
        editor.setSelection(selection);
        editor.revealRangeInCenter(selection, 1 /* Immediate */);
      } else {
        const pos = {
          lineNumber: selection.startLineNumber,
          column: selection.startColumn,
        };
        editor.setPosition(pos);
        editor.revealPositionInCenter(pos, 1 /* Immediate */);
      }
    }
  };

  // 加载jsx高亮
  const loadJsxSyntaxHighlight = (editor: any, monaco: Monaco) => {
    const monacoJsxSyntaxHighlight = new MonacoJsxSyntaxHighlight(
      getWorker(),
      monaco
    );
    const { highlighter, dispose } =
      monacoJsxSyntaxHighlight.highlighterBuilder({
        editor,
      });

    editor.onDidChangeModelContent(() => {
      highlighter();
    });

    highlighter();

    return { highlighter, dispose };
  };

  /**
   * 初始化加载编辑器的type文件
   * @param editor 编辑器
   * @param monaco monaco实例
   * @param defaultContent 代码
   */
  const setupEditor = async (
    editor: any,
    monaco: any,
    defaultContent: string
  ) => {
    // acquireType on initial load
    editor.onDidChangeModelContent(async () => {
      (await typeHelper).acquireType(editor.getValue());
    });

    const defaults = monaco.languages.typescript.typescriptDefaults;

    // defaults.setCompilerOptions({
    //   jsx: JsxEmit.React,
    //   esModuleInterop: true,
    // });

    const addLibraryToRuntime = (code: string, _path: string) => {
      const path = "file://" + _path;
      defaults.addExtraLib(code, path);

      // don't need to open the file in the editor
      // const uri = monaco.Uri.file(path);
      // if (monaco.editor.getModel(uri) === null) {
      //   monaco.editor.createModel(code, 'javascript', uri);
      // }
    };

    (await typeHelper).addListener("receivedFile", addLibraryToRuntime);

    (await typeHelper).acquireType(defaultContent);
  };

  return {
    setupEditor,
    doOpenEditor,
    loadJsxSyntaxHighlight,
  };
}

export default useEditor;
